package main

import (
	"bufio"
	"flag"
	"fmt"
	"net"
)

func Echo(c net.Conn) {
	defer c.Close()
	for {
		line, err := bufio.NewReader(c).ReadString('\n')
		fmt.Printf("recv:%s\n", line)
		//line = line + "end"

		if err != nil {
			fmt.Printf("Failure to read:%s\n", err.Error())
			return
		}
		_, err = c.Write([]byte(line))
		if err != nil {
			fmt.Printf("Failure to write: %s\n", err.Error())
			return
		}
	}
}

var addr = flag.String("addr", ":5000", "tcp service address")

func main() {
	flag.Parse()

	fmt.Printf("Server is ready...\n")
	l, err := net.Listen("tcp", *addr)
	if err != nil {
		fmt.Printf("Failure to listen: %s\n", err.Error())
	}

	for {
		if c, err := l.Accept(); err == nil {
			go Echo(c) //new thread
		}
	}
}
